//
//  LAReviewTableViewCell.m
//  LYLazizDevelopDemo
//
//  Created by xbn_iMac on 2016/10/24.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LAReviewTableViewCell.h"
#import "LAReviewModel.h"
#import "LABaseKeyValueLabelView.h"
#import "HCSStarRatingView.h"
#import "LZReviewPictureModel.h"
#import "LZCustomerUserModel.h"
#import "LZDateFormatterManager.h"
#import "UIButton+EnlargeEdge.h"
#import "UIImageView+WebCache.h"
#import "MJPhotoBrowser.h"
#import "LZReviewTableViewCellReplyView.h"
#import "Masonry.h"

@interface LAReviewTableViewCell ()

@property (weak, nonatomic) IBOutlet UIImageView *imgHead;
@property (weak, nonatomic) IBOutlet UILabel *labName;
@property (weak, nonatomic) IBOutlet UILabel *labTime;
@property (weak, nonatomic) IBOutlet UIView *imgStar;

@property (weak, nonatomic) IBOutlet LABaseKeyValueLabelView *tasteView;
@property (weak, nonatomic) IBOutlet LABaseKeyValueLabelView *atmosphereView;
@property (weak, nonatomic) IBOutlet LABaseKeyValueLabelView *serviceView;

@property (weak, nonatomic) IBOutlet UILabel *labReview;
@property (weak, nonatomic) IBOutlet UIButton *btnMore;
@property (weak, nonatomic) IBOutlet UIView *reviewImage;
@property (weak, nonatomic) IBOutlet LZReviewTableViewCellReplyView *replyView;
@property (weak, nonatomic) IBOutlet UIView *bottomLine;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tasteViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineToLabReviewConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *reviewButtonMoreBottomConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *reviewImageHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *reviewButtonMoreTopConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *replyViewHeightConstraint;

@property (weak, nonatomic) HCSStarRatingView *starRatingView;

@end

@implementation LAReviewTableViewCell


- (UILabel *)getReviewLabel{
    return self.labReview;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.imgHead.layer.masksToBounds = YES;
    
    [self.btnMore setEnlargeEdge:20.0f];
    
    self.labReview.preferredMaxLayoutWidth = CGRectGetWidth([[UIScreen mainScreen] bounds])-74;
    self.imgStar.backgroundColor = [UIColor clearColor];
    
    [self.tasteView setKey:@"1" andValue:@"1"];
    self.tasteViewHeightConstraint.constant = [self.tasteView intrinsicContentSize].height;


    /*
     ==========================================Star =================================================
     */
    
    [self initStarView];
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)initStarView {
    int number = 5;
    HCSStarRatingView *star = [[HCSStarRatingView alloc]initWithFrame:CGRectZero];
    star.maximumValue = number;
    star.minimumValue = 0;
    star.spacing = 2.5;
    star.allowsHalfStars = YES;
    star.accurateHalfStars = YES;
    star.tintColor = UIColorFromRGB(0xF08F4D, 1);
    star.userInteractionEnabled = NO;
    
    self.starRatingView = star;
    
    [self.imgStar addSubview:star];
    
    [star makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.imgStar);
    }];
}

- (void)setHeadImageType:(HeadImageType)headImageType {
    _headImageType = headImageType;
    if (headImageType == HeadImageType_User) {
        self.imgHead.layer.cornerRadius = 22;
    }
    else if (headImageType == HeadImageType_Video) {
        self.imgHead.layer.cornerRadius = 4;
    }
    else if (headImageType == HeadImageType_Restaurants) {
        self.imgHead.layer.cornerRadius = 4;
    }
}

- (void)setIsHideBottomLine:(BOOL)isHideBottomLine {
    _isHideBottomLine = isHideBottomLine;
    self.bottomLine.hidden = isHideBottomLine;
}

-(void)setEntity:(LAReviewModel *)entity {

    _entity = entity;
    
    // 头像和昵称
    if (self.headImageType == HeadImageType_User) {
        // 用户类
        [self.imgHead sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,entity.customerUser.userPhoto]] placeholderImage:[UIImage imageNamed:@"lz_user_placehoiderImage"]];

        self.labName.text = entity.customerUser.nickname;

    }
    else if (self.headImageType == HeadImageType_Video) {
        // 视频类
        [self.imgHead sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,entity.videoPhoto]] placeholderImage:[UIImage imageNamed:@"lz_other_placehoiderImage"]];
        
        self.labName.text = entity.promotionTitle;

    }
    else if (self.headImageType == HeadImageType_Restaurants) {
        // 餐厅类
        [self.imgHead sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,entity.sellerPhoto]] placeholderImage:[UIImage imageNamed:@"lz_other_placehoiderImage"]];
        
        self.labName.text = entity.restaurant_name;

    }
    
    // 创建时间
    self.labTime.text = [[LZDateFormatterManager shareInstance] stringFromStringNormalHaveLineyyyyMMdd:entity.createTime];
    
    // 星星指数
    self.starRatingView.value = entity.commentScore;
    
    // 评分
    if (self.reviewType == ReviewType_Restaurants) {
        
        [self.tasteView setKey:[NSString stringWithFormat:@"%@:",LZLocalizedString(@"taste", nil)] andValue:[NSString stringWithFormat:@"%ld",entity.commentTaste]];
        [self.atmosphereView setKey:[NSString stringWithFormat:@"%@:",LZLocalizedString(@"atmosphere", nil)] andValue:[NSString stringWithFormat:@"%ld",entity.commentEnvironment]];
        [self.serviceView setKey:[NSString stringWithFormat:@"%@:",LZLocalizedString(@"service", nil)] andValue:[NSString stringWithFormat:@"%ld",entity.commentService]];
        
        self.tasteView.hidden = NO;
        self.atmosphereView.hidden = NO;
        self.serviceView.hidden = NO;
        
        self.lineToLabReviewConstraint.constant = 15 + [self.tasteView intrinsicContentSize].height + 18;
    }
    else if (self.reviewType == ReviewType_Video) {
        
        [self.tasteView setKey:@"1" andValue:@"1"];
        [self.atmosphereView setKey:@"1" andValue:@"1"];
        [self.serviceView setKey:@"1" andValue:@"1"];
        
        self.tasteView.hidden = YES;
        self.atmosphereView.hidden = YES;
        self.serviceView.hidden = YES;
        
        self.lineToLabReviewConstraint.constant = 15;
    }
    
   
    // 评论内容
    self.labReview.text = entity.commentContent;

    // 计算单行的Size
    CGSize sizetemp = [@"a" sizeWithAttributes:@{NSFontAttributeName:self.labReview.font}];
    self.labReview.numberOfLines = 0;
    // 计算labreview的高度
    CGFloat labReviewHeight = [self.labReview intrinsicContentSize].height;
    // 计算行数
    NSInteger colomNumber = labReviewHeight/sizetemp.height;

    self.btnMore.hidden = (colomNumber<=3);
    self.reviewButtonMoreTopConstraint.constant = (self.btnMore.isHidden?-CGRectGetHeight(self.btnMore.bounds):5);

    if (entity.labReviewNumberOfLine == 0) {
        self.btnMore.selected = YES;
    }
    else {
        self.btnMore.selected = NO;
    }
    
    self.labReview.numberOfLines = entity.labReviewNumberOfLine;
    
    // 回复模块的view
    self.replyView.isMessageCenter = self.isMessageCenter;
    [self.replyView setReplyText:entity.commentReview andReplyTime:entity.replyTime];
    
    self.replyViewHeightConstraint.constant = self.replyView.intrinsicContentSize.height;
    
    for (UIView *a in self.reviewImage.subviews) {
        [a removeFromSuperview];
    }
    [self createReviewImageview:entity.commentPhotoAlbums];
}

- (IBAction)btnMoreClickAction:(UIButton*)sender {
    sender.selected = !sender.selected;
    NSLog(@"%d",sender.selected);
    if (sender.selected) {
        self.labReview.numberOfLines = 0;
    }
    else {
        self.labReview.numberOfLines = 3;
    }
    
    self.entity.labReviewNumberOfLine = self.labReview.numberOfLines;
    
    
    if ([self.delegate respondsToSelector:@selector(refreshCellHeight:)] && self.delegate) {
        [self.delegate refreshCellHeight:self.indexPath];
    }
}

-(void)createReviewImageview:(NSArray*)images {
    if (images.count == 0) {
        self.reviewButtonMoreBottomConstraint.constant = 20 + (self.replyView.isHidden?0:(self.replyViewHeightConstraint.constant+20));
        self.reviewImageHeightConstraint.constant = 0;

        return;
    }
    
    float width = 60.0*CGRectGetWidth([UIScreen mainScreen].bounds)/375.0;
    
    float padding = (CGRectGetWidth([UIScreen mainScreen].bounds)-10.0-44-15.0-width*4.0-10.0)/3.0;
    
    int rowNum = 4; // 每行的图片的最大数
    
    UIImageView *lastView = nil;
    
    int row = 0;    // 行数
    int rank = 0;    // 列数
    
    for (int i = 0; i<images.count; i++) {
        
        LZReviewPictureModel *photoModel = images[i];
        
        UIImageView *imgView = [[UIImageView alloc] init];
        imgView.backgroundColor = UIColorFromRGB(0xeaeaea, 1);
        imgView.userInteractionEnabled = YES;
        imgView.layer.cornerRadius = 4;
        imgView.clipsToBounds = YES;
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.tag = i;
        [imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,photoModel.photo]] placeholderImage:[UIImage imageNamed:@"lz_other_placehoiderImage"]];
        [self.reviewImage addSubview:imgView];
        lastView = imgView;
        
        [imgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoTap:)]];
        
        row = i/rowNum+1;    // 行数
        rank = (i-(row-1)*rowNum)+1;    // 列数
        
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.and.height.mas_equalTo(width);
            if (row == 1) {
                make.top.equalTo(self.reviewImage.mas_top);
            }
            else {
                make.top.equalTo(self.reviewImage.mas_top).offset((width+padding)*(row-1));
            }
            if (rank == 1) {
                make.leading.equalTo(@0);
            }
            else {
                make.leading.equalTo(self.reviewImage.mas_leading).offset((width+padding)*(rank-1));
            }
        }];
    }
    
    CGFloat reviewImageHeight = row*width+(row-1)*padding;
    
    self.reviewImageHeightConstraint.constant = reviewImageHeight;

    self.reviewButtonMoreBottomConstraint.constant = 20 + reviewImageHeight + 20 + (self.replyView.isHidden?0:(self.replyViewHeightConstraint.constant+20));
}

//点击预览图片
- (void)photoTap:(UITapGestureRecognizer *)recognizer
{
    //1.创建图片浏览器
    MJPhotoBrowser *brower = [[MJPhotoBrowser alloc] init];
    
    //2.告诉图片浏览器显示所有的图片
    NSMutableArray *photos = [NSMutableArray array];
    for (int i = 0 ; i < self.entity.commentPhotoAlbums.count; i++) {
        LZReviewPictureModel *model = self.entity.commentPhotoAlbums[i];
        //传递数据给浏览器
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,model.maxPhoto]];
        photo.srcImageView = (UIImageView*)recognizer.view; //设置来源哪一个UIImageView
        [photos addObject:photo];
    }
    brower.photos = photos;
    
    //3.设置默认显示的图片索引
    brower.currentPhotoIndex = recognizer.view.tag;
    
    //4.显示浏览器
    [brower show];
}



@end
